<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .active {
      background-color: #f0f0f0;
    }
  </style>
</head>
<body>
  <div id="app">
    <input
      type="text"
      placeholder="请输入你的问题"
      v-model="key"
      @keyup.up="up"
      @keyup.down="down"
      @keyup.enter="open"
    >
    <ul>
      <li v-for="(item, index) in resList" :key="index" :class="{active: selectIndex == index}">
        {{item}}
      </li>
    </ul>
  </div>
  <script src="../vue.js"></script>
  <script>
    let vm = new Vue({
      el: '#app',
      data: {
        // 搜素的关键字
        key: '',
        // 结果列表
        resList: [],
        // 默认别选择的项
        selectIndex: -1
      },
      watch: {
        key(val) {
          // 创建script元素
          let script = document.createElement('script');
          // 添加地址，地址就是接口
          script.src = 'http://suggestion.baidu.com/su?cb=callback&wd='+val;
          // 添加到页面中
          document.body.appendChild(script);
        }
      },
      methods: {
        up() {
          // 按上箭头
          this.selectIndex<1 ? this.selectIndex = 4 : this.selectIndex --
        },
        down() {
          // 按下箭头
          this.selectIndex>3 ? this.selectIndex = 0 : this.selectIndex++
        },
        open() {
          // 打开搜素结果页
          window.open('http://www.baidu.com/s?wd='+this.resList[this.selectIndex])
        }
      },
    })
    // 百度的回调函数
    function callback(res) {
      // 只要前五条数据
      let arr = res.s.filter((item, index) => {
        return index<5
      })
      // 不用this，用vm
      vm.resList = arr;
    }
  </script>
</body>
</html>